package com.accenture.fd.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.accenture.fd.dto.ExportExcelItemDto;
import com.accenture.fd.dto.ExportExcelResultDto;
import com.accenture.fd.service.ExportDtoExcelService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

@CrossOrigin
@RestController
public class ExportDtoExcelController {

	@Autowired
	private ExportDtoExcelService exportDtoExcelService;

	@RequestMapping("/export_dto_Excel")
	public void exportDtoExcel(HttpServletResponse response,@RequestBody String filePath) throws UnsupportedEncodingException, IOException {

		//String content = new String(file.getBytes(),"UTF-8");
//		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
		String lineTxt="";
//		while ((lineTxt=bufferedReader.readLine())!=null){
			ExportExcelResultDto dto = exportDtoExcelService.createDtoExcel(filePath);

			// 编辑数据
			List<ExportExcelItemDto> list = dto.getExportExcelItemDtoList();

			// 创建writer，默认创建xls格式 true代表xlsx
			ExcelWriter writer = ExcelUtil.getWriter(true);

			String classDoc = dto.getClassDoc();

			String name = classDoc + "_DTO仕様書";

			//标题
			List<String> rowData = CollectionUtil.newArrayList("序号","详细","名称","类型");
			writer.writeHeadRow(rowData);

			/* 一次性写出内容，使用默认样式，强制输出标题 */
			writer.write(list, true);

			//设置sheet名
			writer.renameSheet("クラス仕様書");

			/* response为HttpServletResponse对象 */
			response.setContentType("application/vnd.ms-excel;charset=utf-8");

			String file_name = new String(name.getBytes(), "ISO-8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + file_name + ".xlsx");

			ServletOutputStream out = null;

			try {
				out = response.getOutputStream();
				writer.flush(out, true);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				writer.close();
			}
			IoUtil.close(out);
//		}

	}

}
